package com.kaifamiao.service.impl;

import com.kaifamiao.entity.User;
import com.kaifamiao.exception.ServiceException;
import com.kaifamiao.repository.UserRepository;
import com.kaifamiao.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepo;

    public String encrypt(final String source,final String salt){
        // 首先对原始密码进行加密
        String encrypted = DigestUtils.sha1Hex(source);
        StringBuilder builder = new StringBuilder( encrypted );
        // 在加密后的字符序列指定位置插入盐值
        builder.insert( 20, salt );
        // 获得插入盐值后的字符串
        String inserted = builder.toString();
        // 对插入盐值后的字符串进行加密
        return DigestUtils.sha1Hex( inserted );
    }

    @Override
    public boolean save(User user) throws ServiceException {
        try {
            // 随机生成盐值并设置到User实例中
            user.setSalt(RandomStringUtils.randomAlphanumeric(8));
            // 对原始密码加密后重新设置到User实例中
            user.setPassword(encrypt(user.getPassword(),user.getSalt()));
            // 保存user
            userRepo.save(user);
            return user.getId() != null ;
        } catch ( Exception cause ) {
            throw new ServiceException( "保存失败", cause );
        }
    }

    @Override
    public User find(Integer id) throws ServiceException {
        try {
            Optional<User> optional = userRepo.findById(id);
            return optional.get();
        } catch ( Exception cause ) {
            throw new ServiceException("查询失败", cause);
        }
    }

}
